<template>
  <!-- 药品管理 -->
  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick" @update="updateTree" @save="saveTree"
              @del="delTree" :filter-node-method="filterNodeMethod" />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud :option="option" :search.sync="search" :table-loading="loading" :data="data" ref="crud" v-model="form"
          :permission="permissionList" @row-del="rowDel" @row-update="rowUpdate" @row-save="rowSave"
          :before-open="beforeOpen" :page.sync="page" @search-change="searchChange" @search-reset="searchReset"
          @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
          @refresh-change="refreshChange" @on-load="onLoad">
          <template slot="state" slot-scope="scope">
            <avue-switch :value="scope.row.state" @click="rowState(scope.row)"></avue-switch>
          </template>
        </avue-crud>

      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
import { getList, getDetail, add, update, remove, getDruCategoryTree, addDruCategory, updateDruCategory, removeDruCategory } from "@/api/infoManagement/drugManage";
import { mapGetters } from "vuex";
import website from "@/config/website";

export default {
  data() {
    return {
      uploadUrl: 'http://123.60.168.86:8302/',
      categoryId: '',
      treeData: [],
      treeOption: {
        nodeKey: 'id',
        // lazy: true,
        // treeLoad: function (node, resolve) {
        //   const parentCode = (node.level === 0) ? "00" : node.data.id;
        //   getLazyTree(parentCode).then(res => {
        //     resolve(res.data.data.map(item => {
        //       return {
        //         ...item,
        //         leaf: !item.hasChildren
        //       }
        //     }))
        //   });
        // },
        defaultExpandAll: true,
        formOption: {
          labelWidth: 100,
          column: [{
            label: '分类名称',
            prop: 'name'
          }],
        },
        addBtn: true,
        menu: true,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children'
        }

      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 5,
        border: true,
        index: true,
        viewBtn: true,
        selection: false,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "药品名称",
            prop: "name",
            search: true,
            rules: [{
              required: true,
              message: "请输入药品名称",
              trigger: "blur"
            }],
          },
          {
            label: "药品厂家",
            prop: "manufactor",
            rules: [{
              required: true,
              message: "请输入药品厂家",
              trigger: "blur"
            }],
          },
          {
            label: "药品数量",
            prop: "quantity",
            rules: [{
              required: true,
              message: "请输入药品数量",
              trigger: "blur"
            }],
          },
          // {
          //   label: '附件上传',
          //   prop: 'attachFile',
          //   type: 'upload',
          //   drag: true,
          //   loadText: '模板上传中，请稍等',
          //   span: 24,
          //   propsHttp: {
          //     res: 'data'
          //   },
          //   action: "/api/blade-resource/oss/endpoint/put-file?code=minio"
          // }

          {
            label: '照片',
            prop: 'picture',
            type: 'upload',
            drag: true,
            listType: 'picture-img',
            loadText: '图片上传中，请稍等',
            span: 24,
            tip: '只能上传jpg/png格式的图片',
            propsHttp: {
              res: 'data',
              url: 'link',
            },
            action: "/api/blade-resource/oss/endpoint/put-file?code=minio"
          },
        ],
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.post_add, false),
        // viewBtn: this.vaildData(this.permission.post_view, false),
        // delBtn: this.vaildData(this.permission.post_delete, false),
        // editBtn: this.vaildData(this.permission.post_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  created() {
    this.initTree()
  },
  methods: {
    filterNodeMethod(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    delTree(data, done) {
      console.log('删除回调', data,);
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeDruCategory(data.id);
        })
        .then(() => {
          done()
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    updateTree(node, data, done, loading) {
      console.log('更新回调', node, data,);
      updateDruCategory(data).then(() => {
        this.initTree()
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    saveTree(node, data, done, loading) {
      console.log('新增回调', node, data, this.categoryId);
      addDruCategory({
        name: data.name,
        parentId: this.categoryId
      }).then(() => {
        this.initTree()
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    nodeClick(data) {
      this.categoryId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    initTree() {
      this.treeData = [];
      getDruCategoryTree(this.topCode).then(res => {
        this.treeData = res.data.data.map(item => {
          return {
            ...item,
            leaf: !item.hasChildren
          }
        })
      });
    },
    rowSave(row, done, loading) {
      const item = {
        ...row,
        categoryId: this.categoryId
      }
      add(item).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      // if (["add"].includes(type)) {
      //   if (this.categoryId == '') {
      //     this.$message({
      //       type: "warning",
      //       message: "请选择需要添加药品的所属类型 ！！！"
      //     });
      //     return;
      //   }
      // }
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query, {
        categoryId: this.categoryId
      })).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
